package com.fdb.efp.console.api.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fdb.basic.framework.core.constant.ApplicationConstance;
import com.fdb.basic.framework.core.constant.ResponseData;
import com.fdb.basic.framework.core.util.TimeUtil;
import com.fdb.basic.framework.core.vo.EngineHttpRequestVO;
import com.fdb.basic.framework.web.util.HttpClientUtil;
import com.fdb.efp.console.service.facade.SequenceService;
import com.fdb.efp.console.common.ConsoleConstant;
import com.fdb.efp.console.common.constance.FlowConstance;
import com.fdb.efp.console.executor.util.AbstractController;
import com.fdb.efp.console.service.FlowCommonService;
import com.fdb.efp.console.service.FlowRepulseUtil;
import com.fdb.efp.console.service.facade.BizFlowInfoService;
import com.fdb.efp.console.service.facade.FlowUrlConfigService;
import com.fdb.efp.console.service.vo.BizFlowInfoVO;
import com.fdb.efp.console.service.facade.ColltWriteOffAppService;
import com.fdb.efp.console.service.vo.ColltWriteOffAppVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@RestController
@RequestMapping("/api")
public class ColltWriteOffAppApprController extends AbstractController {

	@Autowired
	@Qualifier("colltWriteOffAppService")
	private ColltWriteOffAppService colltWriteOffAppService;

	@Autowired
	@Qualifier("dbSeqService")
	private SequenceService sequenceService;

	@Autowired
	private FlowCommonService flowCommonService;

	@Autowired
	@Qualifier("flowRepulseUtil")
	private FlowRepulseUtil flowRepulseUtil;

	@Autowired
	@Qualifier("bizFlowInfoService")
	private BizFlowInfoService bizFlowInfoService;

	@Autowired
	@Qualifier("flowUrlConfigService")
	private FlowUrlConfigService flowUrlConfigService;

	/**
	 * 修改数据-保存
	 * @author xiezw
	 * @params  * @param vo
	 * @return com.fdb.basic.framework.core.constant.ResponseData<java.util.List<com.fdb.efp.console.service.vo.ColltWriteOffAppVO>>
	 * @date 2020/3/19 15:12
	 * @version 0.1
	 */
	@RequestMapping(value = "/collt/write/off/app",method = RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateColltWriteOffApp(@RequestBody ColltWriteOffAppVO colltWriteOffAppVO){
		int outputVo = 0;
		setUserInfoToVO(colltWriteOffAppVO);
		ColltWriteOffAppVO itColltWriteOffAppVO = new ColltWriteOffAppVO();
		itColltWriteOffAppVO.setBizSerno(colltWriteOffAppVO.getBizSerno());
		itColltWriteOffAppVO.setLastUpdateTime(TimeUtil.getCurrentDateTime());
		itColltWriteOffAppVO.setLastUpdateUser(colltWriteOffAppVO.getLoginUserId());
		outputVo = colltWriteOffAppService.updateByCondition(colltWriteOffAppVO);
		return setResponseMessage(outputVo,"保存数据成功", ApplicationConstance.SUCCESS,true);
	}

	/**
	 * 修改数据-提交
	 * @author xiezw
	 * @params  * @param vo
	 * @return com.fdb.basic.framework.core.constant.ResponseData<java.util.List<com.fdb.efp.console.service.vo.ColltWriteOffAppVO>>
	 * @date 2020/3/19 15:12
	 * @version 0.1
	 */
	@RequestMapping(value = "/collt/write/off/app/submit",method = RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> upSubmitColltWriteOffApp(@RequestBody ColltWriteOffAppVO colltWriteOffAppVO){
		int outputVo = 0;
		setUserInfoToVO(colltWriteOffAppVO);
		updateColltWriteOffApp(colltWriteOffAppVO);
		List<ColltWriteOffAppVO> list = colltWriteOffAppService.queryByPk(colltWriteOffAppVO);
		ResponseData<Integer> integerResponseData = submit(list);
		if(!integerResponseData.isSuccess()){
			outputVo = -1;
			return setResponseMessage(outputVo, integerResponseData.getMessage(),ApplicationConstance.FAILURE,false);
		}
		return setResponseMessage(outputVo,"提交数据成功", ApplicationConstance.SUCCESS,true);

	}

	/**
	 * 新增数据-保存
	 * @author xiezw
	 * @params  * @param vo
	 * @return com.fdb.basic.framework.core.constant.ResponseData<java.util.List<com.fdb.efp.console.service.vo.ColltWriteOffAppVO>>
	 * @date 2020/3/10 15:12
	 * @version 0.1
	 */
	@RequestMapping(value = "/collt/write/off/app",method = RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> insertColltWriteOffApp(@RequestBody List<ColltWriteOffAppVO> colltWriteOffAppVOs){
		int outputVo = 0;
		setUserInfoToVO(colltWriteOffAppVOs.get(0));
		if (check(colltWriteOffAppVOs)){
			outputVo = -1;
			return setResponseMessage(outputVo,"选中数据含有未完成的核销申请操作！", ApplicationConstance.FAILURE,false);
		}
		try {
			//  核销流水号
			String tSeq = colltWriteOffAppVOs.get(0).getBizSerno();
			if (Objects.isNull(tSeq) || tSeq.equals("")){
				tSeq = sequenceService.getSequence("WO_SEQ_ID","null","null");
			}else{
				tSeq = colltWriteOffAppVOs.get(0).getBizSerno();
			}
			for (ColltWriteOffAppVO item : colltWriteOffAppVOs) {
				item.setCreateUserCode(colltWriteOffAppVOs.get(0).getLoginUserId());
				item.setCreateTime(TimeUtil.getCurrentDateTime());
				item.setLastUpdateUser(colltWriteOffAppVOs.get(0).getLoginUserId());
				item.setLastUpdateTime(TimeUtil.getCurrentDateTime());
				item.setBizSerno(tSeq);
				item.setAprvStatus(ConsoleConstant.APRV_STATUS_01);
				outputVo = colltWriteOffAppService.insertColltWriteOffApp(item);
			}
		} catch (Exception e) {
			logger.error("********************************************插入数据出错，异常信息为：", e.getMessage());
			outputVo = -1;
			return setResponseMessage(outputVo,"插入数据异常", ApplicationConstance.FAILURE,false);
		}
		return setResponseMessage(outputVo,"保存数据成功", ApplicationConstance.SUCCESS,true);

	}

	/**
	 * 新增数据提交
	 * @author xiezw
	 * @params  * @param null
	 * @return
	 * @date 2020/3/12 9:10
	 * @version 0.1
	 */
	@RequestMapping(value = "/collt/write/off/app/submit",method = RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> submitColltWriteOffApp(@RequestBody List<ColltWriteOffAppVO> colltWriteOffAppVOs){
		int outputVo = 0;
		setUserInfoToVO(colltWriteOffAppVOs.get(0));
        ResponseData<Integer> integerResponseData = insertColltWriteOffApp(colltWriteOffAppVOs);
        if(!integerResponseData.isSuccess()){
            outputVo = -1;
            return setResponseMessage(outputVo, integerResponseData.getMessage(),ApplicationConstance.FAILURE,false);
        }
		integerResponseData = submit(colltWriteOffAppVOs);
		if(!integerResponseData.isSuccess()){
			outputVo = -1;
			return setResponseMessage(outputVo, integerResponseData.getMessage(),ApplicationConstance.FAILURE,false);
		}
		return setResponseMessage(outputVo,"提交数据成功", ApplicationConstance.SUCCESS,true);
	}

	private ResponseData<Integer> submit(List<ColltWriteOffAppVO> colltWriteOffAppVOs){
		int outputVo = 0;
		if(colltWriteOffAppVOs.get(0).getAprvStatus().equals(ConsoleConstant.APRV_STATUS_05)){
			flowRepulseUtil.cleanRepulseAllInfo(colltWriteOffAppVOs.get(0).getBizSerno());
		}
		logger.info("即将发起核销申请审批流程，信息为:" + JSON.toJSONString(colltWriteOffAppVOs));
		String eventId = "mColltWriteOffAppEnter";
		String flowId = "FW20200312000000003";
		// 流程岗位校验
		if (!flowCommonService.dutyFlowCheck(eventId,flowId)){
			outputVo = -1;
			return setResponseMessage(outputVo,"发起核销申请审批流程失败!原因: 流程岗位已失效", ApplicationConstance.FAILURE,false);
		}
		BizFlowInfoVO bizFlowInfoVO = new BizFlowInfoVO();
		bizFlowInfoVO.setBizFlowType(FlowConstance.BIZ_FLOW_TYPE_10); // 贷后催收流转类型
		bizFlowInfoVO.setBizFlowId(flowId);
		List<BizFlowInfoVO> listFlow = bizFlowInfoService.queryBizFlowInfoByFlowType(bizFlowInfoVO);
		logger.info("查询到的业务流程参数为：" + JSONObject.toJSONString(listFlow));
		if (Objects.nonNull(listFlow) && listFlow.size() > 0) {
			bizFlowInfoVO = listFlow.get(0);
			flowId = bizFlowInfoVO.getBizFlowId();  // 得到业务流转ID
		} else {
			//保存数据成功，提交失败
			outputVo = -1;
			return setResponseMessage(outputVo,"发起流程失败，已经为您保存数据", ApplicationConstance.FAILURE,false);
		}
		EngineHttpRequestVO eVo = new EngineHttpRequestVO();
		// 业务法人机构
		eVo.setBizLagelOrgCode(this.getUserInfo().getOrgInfo().getOrgCode());
		// 业务流水号
		eVo.setE_bizSerno(colltWriteOffAppVOs.get(0).getBizSerno());
		eVo.setFlowId(flowId);
		//事件ID
		eVo.setData(colltWriteOffAppVOs);
		eVo.setEventId(eventId);
		eVo.setG_bizSerno(colltWriteOffAppVOs.get(0).getBizSerno());
		try {
			HttpClientUtil.callFlowEngine(flowUrlConfigService.getRestfulSyncStartEventUrl(), eVo, String.class);
			ColltWriteOffAppVO colltWriteOffAppVO = new ColltWriteOffAppVO();
			colltWriteOffAppVO.setBizSerno(colltWriteOffAppVOs.get(0).getBizSerno());
			colltWriteOffAppVO.setAprvStatus(ConsoleConstant.APRV_STATUS_02);
			colltWriteOffAppVO.setLastUpdateTime(TimeUtil.getCurrentDateTime());
			colltWriteOffAppVO.setLastUpdateUser(colltWriteOffAppVOs.get(0).getLoginUserId());
			outputVo = colltWriteOffAppService.updateByCondition(colltWriteOffAppVO);
		} catch (Exception e) {
			// 发起失败
			e.printStackTrace();
			logger.error("CaseDistrRatioVO", e.getMessage());
			outputVo = -1;
			return setResponseMessage(outputVo, "发起案件分配比例审批流程失败!原因: " + e.getMessage(), ApplicationConstance.FAILURE,false);
		}
		return setResponseMessage(outputVo,"提交数据成功", ApplicationConstance.SUCCESS,true);
	}

	/**
	 * 校验是否存在“待发起”、“审批中”、“退回”的核销申请数据 true-存在  false-不存在
	 * @author xiezw
	 * @params  * @param null
	 * @return  Boolean
	 * @date 2020/3/12 9:47
	 * @version 0.1
	 */
	private boolean check(List<ColltWriteOffAppVO> inVos){
		for(ColltWriteOffAppVO item : inVos){
			List<ColltWriteOffAppVO> qs = Optional.ofNullable(colltWriteOffAppService.queryAllByCondition(item)).orElse(new ArrayList<>());
			if (qs.size()<0){
			    continue;
			}
			for (ColltWriteOffAppVO it : qs){
				if (ConsoleConstant.APRV_STATUS_01.equals(it.getAprvStatus()) || ConsoleConstant.APRV_STATUS_02.equals(it.getAprvStatus())
						|| ConsoleConstant.APRV_STATUS_05.equals(it.getAprvStatus())){
					return true;
				}
			}
		}
		return false;
	}

	private ResponseData<Integer> setResponseMessage(int outputVo ,String message, String code, boolean isSuccess) {
		ResponseData<Integer> responseData = new ResponseData<Integer>();
		responseData.setRows(outputVo);
		responseData.setMessage(message);
		responseData.setCode(code);
		responseData.setSuccess(isSuccess);
		return responseData;
	}
}
